<template>
    <div>
        <el-cascader
            :key="version"
            v-model="selectChapterId"
            :show-all-levels="false"
            :clearable="props.clearable !== false"
            :filterable="props.filterable !== false"
            :options="chapterData"
            :props="propsData"
            :append-to-body="appendToBody"
            @change="selectEvent"
        ></el-cascader>
    </div>
</template>
<script>
import { examBase } from "@/layout/mixin/examBase";
import { get } from "@/api/request";
import { treeList2Tree } from "@/utils";

export default {
    mixins: [examBase],
    props: {
        categoryId: {
            type: Number,
            require: false,
            default: null
        },
        chapterId: {
            type: String,
            require: false,
            default: null
        },
        appendToBody: {
            type: Boolean,
            default: true
        },
        props: {
            type: Object,
            require: false,
            default: () => ({})
        }
    },
    data() {
        return {
            selectChapterId: null,
            selectCategoryId: null,
            loading: false,
            propsData: {
                value: "id",
                label: "name",
                emitPath: false,
                checkStrictly: true
            },
            chapterData: [],
            version: 0
        };
    },
    watch: {
        chapterId(chapterId) {
            this.selectChapterId = chapterId;
        },
        categoryId(categoryId) {
            if (categoryId !== null) {
                this.selectCategoryId = categoryId;
                this.loadTreeData();
            }
        },
        chapterData(val) {
            this.version++;
        }
    },
    created() {
        this.selectChapterId = this.chapterId;
        this.selectCategoryId = this.categoryId;
        this.loadTreeData();
    },
    methods: {
        loadTreeData() {
            let categoryId = this.selectCategoryId;
            if (categoryId !== null) {
                get("/exam/chapter/list", {
                    categoryId,
                    size: 1000,
                    tree: false
                })
                    .then(res => {
                        this.chapterData = treeList2Tree(res);
                    })
                    .finally(() => {
                        this.version++;
                    });
            }
        },
        selectEvent(vl) {
            this.$emit("update:chapterId", vl);
        }
    }
};
</script>
